package com.hsd.whb.security;

import com.hsd.whb.entity.Manager;
import com.hsd.whb.repository.ManagerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class HwbManagerUserDetailsService implements UserDetailsService {

    @Autowired
    private ManagerRepository managerRepository;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Manager manager = managerRepository.findByUsername(username);
        if (manager != null) {
            List<GrantedAuthority> authorities = new ArrayList<>();
            if (username.equals("root")) {
                authorities.add(new SimpleGrantedAuthority("ROLE_ROOT"));
                authorities.add(new SimpleGrantedAuthority("ROLE_MANAGER"));
            } else {
                authorities.add(new SimpleGrantedAuthority("ROLE_MANAGER"));
            }
            return new User(username, manager.getPassword(), authorities);
        }
        throw new UsernameNotFoundException("用户名不存在");
    }


}
